package com.ssyt.examinationsystem.controller;

import com.ssyt.examinationsystem.entity.*;
import com.ssyt.examinationsystem.service.*;
import com.ssyt.examinationsystem.service.impl.*;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Iterator;

/**
 * Servlet implementation class ImportController
 */
@MultipartConfig
public class ImportController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImportController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 调用选择，填空，判断，主观题的业务对象
        IChoiceInfoService choiceService = new ChoiceInfoServiceImpl();
        IBlankInfoService blankService = new BlankInfoServiceImpl();
        IJudgeInfoService judgeService = new JudgeInfoServiceImpl();
        ISubjectiveInfoService subjectiveService = new SubjectiveInfoServiceImpl();
        // 调用成绩的业务对象
        IScoreInfoService scoreService = new ScoreInfoServiceImpl();
        // 调用学生的业务对象
        IStudentInfoService stuService = new StudentInfoServiceImpl();
        // 调用教师的业务对象
        ITeacherInfoService teaService = new TeacherInfoServiceImpl();

        PrintWriter out = response.getWriter();
        // 获取上传的文件流
        Part part = request.getPart("excelFile");

        // 获取地址栏上的flag值
        String flag = request.getParameter("flag");
        if ("choice".equals(flag)) {
            importChoice(part, choiceService, request, response, out);
        } else if ("question".equals(flag)) {
            importQuestion(part, blankService, judgeService, subjectiveService, request, response, out);
        } else if ("score".equals(flag)) {
            importScore(part, scoreService, request, response, out);
        } else if ("student".equals(flag)) {
            importStudent(part, stuService, request, response, out);
        } else if ("teacher".equals(flag)) {
            importTeacher(part, teaService, request, response, out);
        }

        out.flush();
        out.close();
    }

    /**
     * 导入教师信息
     *
     * @param part
     * @param teaService
     * @param request
     * @param response
     * @param out
     * @throws IOException
     */
    private void importTeacher(Part part, ITeacherInfoService teaService, HttpServletRequest request,
                               HttpServletResponse response, PrintWriter out) throws IOException {
        InputStream is = part.getInputStream();
        // 获取上传文件的名称
        String disposition = part.getHeader("Content-Disposition");
        // 通过";"分割字符串
        String fileNameString = disposition.split(";")[2];
        // 通过"="分割出文件名称字符串
        fileNameString = fileNameString.split("=")[1];
        // 通过"\"判断是否需要再次分割
        if (fileNameString.lastIndexOf("\\") > 0) {
            fileNameString = fileNameString.substring(fileNameString.lastIndexOf("\\") + 1);
        }
        // 处理分割字符串获取文件名称
        String fileName = fileNameString.replaceAll("\"", "");
        // 获取文件扩展名(后缀名)
        String extensionName = fileName.substring(fileName.lastIndexOf("."));
        // 定义excel的类型数组
        String[] excelTypes = {".xls", ".xlsx"};
        // 定义文件类型是否匹配标志
        boolean flag = false;
        // 判断导入文件类型是否为excel类型
        for (String value : excelTypes) {
            if (value.equals(extensionName)) {
                flag = true;
                break;
            }
        }

        // 定义一个工作簿接口对象
        Workbook wb = null;
        boolean mark = false;
        // 如果类型匹配执行
        if (flag) {
            // XSSF 2007版本以上（包含2007）
            if (".xlsx".equals(extensionName)) {
                wb = new XSSFWorkbook(is);
            } else { // HSSF 2007版本以下
                wb = new HSSFWorkbook(is);
            }
            // 获取当前工作簿里面有多少个表格
            Sheet sheet = wb.getSheet("teacher");

            // 获取当前单元格中的行数
            Iterator<Row> rows = sheet.rowIterator();
            rows.next(); // 跳过第一行
            while (rows.hasNext()) {
                Row row = rows.next();
                // 获取每个单元格中的值
                String teaName = String.valueOf(getCellValue(row.getCell(0)));
                teaName = URLDecoder.decode(teaName, "UTF-8");

                String account = String.valueOf(getCellValue(row.getCell(1)));
                // 对网页数据进行转码（网页数据使用了encodeURI()操作）
                account = URLDecoder.decode(account, "UTF-8");

                String password = String.valueOf(getCellValue(row.getCell(2)));
                password = URLDecoder.decode(password, "UTF-8");

                String roleId = String.valueOf(getCellValue(row.getCell(3)));
                roleId = URLDecoder.decode(roleId, "UTF-8");
                roleId = roleId.substring(0, roleId.length() - 2);

                // 创建一个选择题对象，并封装属性
                TeacherInfo tea = new TeacherInfo();
                tea.setAccount(account);
                tea.setPassword(password);

                RoleInfo role = new RoleInfo();
                role.setRoleId(Integer.valueOf(roleId));
                tea.setRole(role);
                tea.setTeaName(teaName);

                // 调用添加选择题的方法
                if (teaService.addTeacherInfo(tea) > 0) {
                    mark = true;
                }
            }
            if (mark) {
                out.print("ok");
            }
        } else {
            out.print("false");
        }
    }

    /**
     * 导入学生信息
     *
     * @param part
     * @param stuService
     * @param request
     * @param response
     * @param out
     * @throws IOException
     */
    private void importStudent(Part part, IStudentInfoService stuService, HttpServletRequest request,
                               HttpServletResponse response, PrintWriter out) throws IOException {
        InputStream is = part.getInputStream();
        // 获取上传文件的名称
        String disposition = part.getHeader("Content-Disposition");
        // 通过";"分割字符串
        String fileNameString = disposition.split(";")[2];
        // 通过"="分割出文件名称字符串
        fileNameString = fileNameString.split("=")[1];
        // 通过"\"判断是否需要再次分割
        if (fileNameString.lastIndexOf("\\") > 0) {
            fileNameString = fileNameString.substring(fileNameString.lastIndexOf("\\") + 1);
        }
        // 处理分割字符串获取文件名称
        String fileName = fileNameString.replaceAll("\"", "");
        // 获取文件扩展名(后缀名)
        String extensionName = fileName.substring(fileName.lastIndexOf("."));
        // 定义excel的类型数组
        String[] excelTypes = {".xls", ".xlsx"};
        // 定义文件类型是否匹配标志
        boolean flag = false;
        // 判断导入文件类型是否为excel类型
        for (String value : excelTypes) {
            if (value.equals(extensionName)) {
                flag = true;
                break;
            }
        }

        // 定义一个工作簿接口对象
        Workbook wb = null;
        boolean mark = false;
        // 如果类型匹配执行
        if (flag) {
            // XSSF 2007版本以上（包含2007）
            if (".xlsx".equals(extensionName)) {
                wb = new XSSFWorkbook(is);
            } else { // HSSF 2007版本以下
                wb = new HSSFWorkbook(is);
            }
            // 获取当前工作簿里面有多少个表格
            Sheet sheet = wb.getSheet("student");

            // 获取当前单元格中的行数
            Iterator<Row> rows = sheet.rowIterator();
            rows.next(); // 跳过第一行
            while (rows.hasNext()) {
                Row row = rows.next();
                // 获取每个单元格中的值
                String account = String.valueOf(getCellValue(row.getCell(0)));
                // 对网页数据进行转码（网页数据使用了encodeURI()操作）
                account = URLDecoder.decode(account, "UTF-8");

                String password = String.valueOf(getCellValue(row.getCell(1)));
                password = URLDecoder.decode(password, "UTF-8");

                String stuClass = String.valueOf(getCellValue(row.getCell(2)));
                stuClass = URLDecoder.decode(stuClass, "UTF-8");

                String roleId = String.valueOf(getCellValue(row.getCell(3)));
                roleId = URLDecoder.decode(roleId, "UTF-8");
                roleId = roleId.substring(0, roleId.length() - 2);

                String stuName = String.valueOf(getCellValue(row.getCell(4)));
                stuName = URLDecoder.decode(stuName, "UTF-8");

                // 创建一个选择题对象，并封装属性
                StudentInfo stu = new StudentInfo();
                stu.setAccount(account);
                stu.setPassword(password);
                stu.setStuClass(stuClass);

                RoleInfo role = new RoleInfo();
                role.setRoleId(Integer.valueOf(roleId));
                stu.setRole(role);
                stu.setStuName(stuName);

                // 调用添加选择题的方法
                if (stuService.addStudentInfo(stu) > 0) {
                    mark = true;
                }
            }
            if (mark) {
                out.print("ok");
            }
        } else {
            out.print("false");
        }
    }

    /**
     * 导入学生成绩
     *
     * @param part
     * @param scoreService
     * @param request
     * @param response
     * @param out
     * @throws IOException
     */
    private void importScore(Part part, IScoreInfoService scoreService, HttpServletRequest request,
                             HttpServletResponse response, PrintWriter out) throws IOException {
        InputStream is = part.getInputStream();
        // 获取上传文件的名称
        String disposition = part.getHeader("Content-Disposition");
        // 通过";"分割字符串
        String fileNameString = disposition.split(";")[2];
        // 通过"="分割出文件名称字符串
        fileNameString = fileNameString.split("=")[1];
        // 通过"\"判断是否需要再次分割
        if (fileNameString.lastIndexOf("\\") > 0) {
            fileNameString = fileNameString.substring(fileNameString.lastIndexOf("\\") + 1);
        }
        // 处理分割字符串获取文件名称
        String fileName = fileNameString.replaceAll("\"", "");
        // 获取文件扩展名(后缀名)
        String extensionName = fileName.substring(fileName.lastIndexOf("."));
        // 定义excel的类型数组
        String[] excelTypes = {".xls", ".xlsx"};
        // 定义文件类型是否匹配标志
        boolean flag = false;
        // 判断导入文件类型是否为excel类型
        for (String value : excelTypes) {
            if (value.equals(extensionName)) {
                flag = true;
                break;
            }
        }

        // 定义一个工作簿接口对象
        Workbook wb = null;
        boolean mark = false;
        // 如果类型匹配执行
        if (flag) {
            // XSSF 2007版本以上（包含2007）
            if (".xlsx".equals(extensionName)) {
                wb = new XSSFWorkbook(is);
            } else { // HSSF 2007版本以下
                wb = new HSSFWorkbook(is);
            }
            // 获取当前工作簿里面有多少个表格
            Sheet sheet = wb.getSheet("score");

            // 获取当前单元格中的行数
            Iterator<Row> rows = sheet.rowIterator();
            rows.next(); // 跳过第一行
            while (rows.hasNext()) {
                Row row = rows.next();
                // 获取每个单元格中的值
                String paperId = String.valueOf(getCellValue(row.getCell(0)));
                // 对网页数据进行转码（网页数据使用了encodeURI()操作）
                paperId = URLDecoder.decode(paperId, "UTF-8");
                paperId = paperId.substring(0, paperId.length() - 2);

                String stuId = String.valueOf(getCellValue(row.getCell(1)));
                stuId = URLDecoder.decode(stuId, "UTF-8");
                stuId = stuId.substring(0, stuId.length() - 2);

                String objectiveScore = String.valueOf(getCellValue(row.getCell(2)));
                objectiveScore = URLDecoder.decode(objectiveScore, "UTF-8");

                String subjectiveScore = String.valueOf(getCellValue(row.getCell(3)));
                subjectiveScore = URLDecoder.decode(subjectiveScore, "UTF-8");

                // 创建一个选择题对象，并封装属性
                ScoreInfo score = new ScoreInfo();

                PaperInfo paper = new PaperInfo();
                paper.setPaperId(Integer.valueOf(paperId));
                score.setPaper(paper);

                StudentInfo stu = new StudentInfo();
                stu.setStuId(Integer.valueOf(stuId));
                score.setStu(stu);

                score.setObjectiveScore(Float.valueOf(objectiveScore));
                score.setSubjectiveScore(Float.valueOf(subjectiveScore));
                // 调用添加选择题的方法
                if (scoreService.addScore(score) > 0) {
                    mark = true;
                }
            }
            if (mark) {
                out.print("ok");
            }
        } else {
            out.print("false");
        }
    }

    private void importQuestion(Part part, IBlankInfoService blankService, IJudgeInfoService judgeService,
                                ISubjectiveInfoService subjectiveService, HttpServletRequest request, HttpServletResponse response,
                                PrintWriter out) throws IOException {
        InputStream is = part.getInputStream();
        // 获取上传文件的名称
        String disposition = part.getHeader("Content-Disposition");
        // 通过";"分割字符串
        String fileNameString = disposition.split(";")[2];
        // 通过"="分割出文件名称字符串
        fileNameString = fileNameString.split("=")[1];
        // 通过"\"判断是否需要再次分割
        if (fileNameString.lastIndexOf("\\") > 0) {
            fileNameString = fileNameString.substring(fileNameString.lastIndexOf("\\") + 1);
        }
        // 处理分割字符串获取文件名称
        String fileName = fileNameString.replaceAll("\"", "");
        // 获取文件扩展名(后缀名)
        String extensionName = fileName.substring(fileName.lastIndexOf("."));
        // 定义excel的类型数组
        String[] excelTypes = {".xls", ".xlsx"};
        // 定义文件类型是否匹配标志
        boolean flag = false;
        // 判断导入文件类型是否为excel类型
        for (String value : excelTypes) {
            if (value.equals(extensionName)) {
                flag = true;
                break;
            }
        }

        // 定义一个工作簿接口对象
        Workbook wb = null;
        boolean mark = false;
        int para = 0;
        // 如果类型匹配执行
        if (flag) {
            // XSSF 2007版本以上（包含2007）
            if (".xlsx".equals(extensionName)) {
                wb = new XSSFWorkbook(is);
            } else { // HSSF 2007版本以下
                wb = new HSSFWorkbook(is);
            }
            // 获取当前工作簿里面有多少个表格
            Sheet sheet = wb.getSheet("blank");
            if (sheet == null) {
                sheet = wb.getSheet("judge");
                para = 1;
            }
            if (sheet == null) {
                sheet = wb.getSheet("subject");
                para = 2;
            }

            // 获取当前单元格中的行数
            Iterator<Row> rows = sheet.rowIterator();
            rows.next(); // 跳过第一行
            while (rows.hasNext()) {
                Row row = rows.next();
                // 获取每个单元格中的值
                String question = String.valueOf(getCellValue(row.getCell(0)));
                // 对网页数据进行转码（网页数据使用了encodeURI()操作）
                question = URLDecoder.decode(question, "UTF-8");

                String answer = String.valueOf(getCellValue(row.getCell(1)));
                answer = URLDecoder.decode(answer, "UTF-8");

                Float courseId1 = Float.valueOf(String.valueOf(getCellValue(row.getCell(2))));
                Integer courseId = (int) Math.floor(courseId1);
                CourseInfo course = new CourseInfo();
                course.setCourseId(courseId);

                if (para == 0) {

                    // 创建一个填空题题对象，并封装属性
                    BlankInfo blank = new BlankInfo();
                    blank.setQuestion(question);
                    blank.setAnswer(answer);
                    blank.setCourse(course);
                    // 调用添加选择题的方法
                    if (blankService.addBlankInfo(blank) > 0) {
                        mark = true;
                    }
                } else if (para == 1) {
                    // 创建一个判断题对象，并封装属性
                    JudgeInfo judge = new JudgeInfo();
                    judge.setQuestion(question);
                    judge.setAnswer(answer);
                    judge.setCourse(course);
                    // 调用添加选择题的方法
                    if (judgeService.addJudgeInfo(judge) > 0) {
                        mark = true;
                    }
                } else if (para == 2) {
                    // 创建一个主观题对象，并封装属性
                    SubjectiveInfo subjective = new SubjectiveInfo();
                    subjective.setQuestion(question);
                    subjective.setAnswer(answer);
                    subjective.setCourse(course);
                    // 调用添加选择题的方法
                    if (subjectiveService.addSubjectiveInfo(subjective) > 0) {
                        mark = true;
                    }
                }

            }
            if (mark) {
                out.print("ok");
            }
        } else {
            out.print("false");
        }
    }

    /**
     * 导入选择题的方法
     *
     * @param choiceService
     * @param request
     * @param response
     * @param out
     * @throws IOException
     * @throws ServletException
     */
    private void importChoice(Part part, IChoiceInfoService choiceService, HttpServletRequest request,
                              HttpServletResponse response, PrintWriter out) throws IOException, ServletException {
        InputStream is = part.getInputStream();
        // 获取上传文件的名称
        String disposition = part.getHeader("Content-Disposition");
        // 通过";"分割字符串
        String fileNameString = disposition.split(";")[2];
        // 通过"="分割出文件名称字符串
        fileNameString = fileNameString.split("=")[1];
        // 通过"\"判断是否需要再次分割
        if (fileNameString.lastIndexOf("\\") > 0) {
            fileNameString = fileNameString.substring(fileNameString.lastIndexOf("\\") + 1);
        }
        // 处理分割字符串获取文件名称
        String fileName = fileNameString.replaceAll("\"", "");
        // 获取文件扩展名(后缀名)
        String extensionName = fileName.substring(fileName.lastIndexOf("."));
        // 定义excel的类型数组
        String[] excelTypes = {".xls", ".xlsx"};
        // 定义文件类型是否匹配标志
        boolean flag = false;
        // 判断导入文件类型是否为excel类型
        for (String value : excelTypes) {
            if (value.equals(extensionName)) {
                flag = true;
                break;
            }
        }

        // 定义一个工作簿接口对象
        Workbook wb = null;
        boolean mark = false;
        // 如果类型匹配执行
        if (flag) {
            // XSSF 2007版本以上（包含2007）
            if (".xlsx".equals(extensionName)) {
                wb = new XSSFWorkbook(is);
            } else { // HSSF 2007版本以下
                wb = new HSSFWorkbook(is);
            }
            // 获取当前工作簿里面有多少个表格
            Sheet sheet = wb.getSheet("choiceInfo");
            if (sheet == null) {
                sheet = wb.getSheet("multiplechoice");
            }
            // 获取当前单元格中的行数
            Iterator<Row> rows = sheet.rowIterator();
            rows.next(); // 跳过第一行
            while (rows.hasNext()) {
                Row row = rows.next();
                // 获取每个单元格中的值
                String question = String.valueOf(getCellValue(row.getCell(0)));
                // 对网页数据进行转码（网页数据使用了encodeURI()操作）
                question = URLDecoder.decode(question, "UTF-8");

                String answerA = String.valueOf(getCellValue(row.getCell(1)));
                answerA = URLDecoder.decode(answerA, "UTF-8");

                String answerB = String.valueOf(getCellValue(row.getCell(2)));
                answerB = URLDecoder.decode(answerB, "UTF-8");

                String answerC = String.valueOf(getCellValue(row.getCell(3)));
                answerC = URLDecoder.decode(answerC, "UTF-8");

                String answerD = String.valueOf(getCellValue(row.getCell(4)));
                answerD = URLDecoder.decode(answerD, "UTF-8");

                String answer = String.valueOf(getCellValue(row.getCell(5)));
                answer = URLDecoder.decode(answer, "UTF-8");

                Float courseId1 = Float.valueOf(String.valueOf(getCellValue(row.getCell(6))));
                Integer courseId = (int) Math.floor(courseId1);
                CourseInfo course = new CourseInfo();
                course.setCourseId(courseId);
                Float choiceType1 = Float.valueOf(String.valueOf(getCellValue(row.getCell(7))));
                Integer choiceType = (int) Math.floor(choiceType1);

                String remark = String.valueOf(getCellValue(row.getCell(8)));
                remark = URLDecoder.decode(remark, "UTF-8");
                // 创建一个选择题对象，并封装属性
                ChoiceInfo choice = new ChoiceInfo();
                choice.setQuestion(question);
                choice.setAnswerA(answerA);
                choice.setAnswerB(answerB);
                choice.setAnswerC(answerC);
                choice.setAnswerD(answerD);
                choice.setAnswer(answer);
                choice.setChoiceType(choiceType);
                choice.setRemark(remark);
                choice.setCourse(course);
                // 调用添加选择题的方法
                if (choiceService.addChoiceInfo(choice) > 0) {
                    mark = true;
                }
            }
            if (mark) {
                out.print("ok");
            }
        } else {
            out.print("false");
        }
    }

    /**
     * 定义定义获取每一个单元格值得方法
     */
    public Object getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        } else {
            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                return cell.getStringCellValue();
            } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                return cell.getNumericCellValue();
            } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
                return cell.getStringCellValue();
            } else if (HSSFDateUtil.isCellDateFormatted(cell)) {
                return cell.getDateCellValue();
            }
        }
        return null;
    }

}
